<template>
  <div class="summary-form">
    <el-form :model="form" label-width="120px" size="small">
      <el-form-item label="评定年份" required>
        <el-date-picker v-model="form.year" type="year" placeholder="选择年份" />
      </el-form-item>

      <el-form-item label="思政得分" required>
        <el-input-number v-model="form.moralScore" :min="0" :max="30" />
      </el-form-item>

      <el-form-item label="学业得分" required>
        <el-input-number v-model="form.academicScore" :min="0" :max="20" />
      </el-form-item>

      <el-form-item label="科研得分" required>
        <el-input-number v-model="form.researchScore" :min="0" :max="50" />
      </el-form-item>

      <el-form-item label="社会服务得分" required>
        <el-input-number v-model="form.serviceScore" :min="0" :max="20" />
      </el-form-item>

      <el-form-item label="综合总分">
        <el-input :value="totalScore" disabled />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="resetForm" style="margin-left: 10px;">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'SummaryForm',
  data() {
    return {
      form: {
        year: new Date().getFullYear(),
        moralScore: 0,
        academicScore: 0,
        researchScore: 0,
        serviceScore: 0
      },
      studentId: null,
      grade: null
    }
  },
  computed: {
    totalScore() {
      return (
        Number(this.form.moralScore || 0) +
        Number(this.form.academicScore || 0) +
        Number(this.form.researchScore || 0) +
        Number(this.form.serviceScore || 0)
      )
    }
  },
  async mounted() {
    this.studentId = Number(localStorage.getItem('studentId'))
    this.grade = Number(localStorage.getItem('gradeYear'))

    if (!this.studentId) {
      ElMessage.error('未检测到学生ID，请重新登录')
      return
    }
    if (!this.grade) {
      ElMessage.warning('未检测到年级，科研得分可能无法自动获取')
    }

    await this.fetchScores()
  },
  methods: {
    async fetchScores() {
      try {
        const [moralRes, academicRes, researchRes, serviceRes] = await Promise.all([
          axios.get(`/api/evaluation/moral/${this.studentId}`, { withCredentials: true }),
          axios.get(`/api/evaluation/academic/${this.studentId}`, { withCredentials: true }),
          this.grade
            ? axios.get(`/api/evaluation/research/${this.studentId}/${this.grade}`, { withCredentials: true })
            : Promise.resolve({ data: 0 }),
          axios.get(`/api/evaluation/service/${this.studentId}`, { withCredentials: true })
        ])

        this.form.moralScore = moralRes.data || 0
        this.form.academicScore = academicRes.data || 0
        this.form.researchScore = researchRes.data || 0
        this.form.serviceScore = serviceRes.data || 0
      } catch (error) {
        console.error('获取分数失败:', error)
        ElMessage.error('自动获取分数失败，请手动填写')
      }
    },

    async handleSave() {
      if (!this.form.year) {
        ElMessage.error('请选择评定年份')
        return
      }

      if (!this.studentId) {
        ElMessage.error('缺少学生ID，无法保存')
        return
      }

      const yearVal = this.form.year instanceof Date
        ? this.form.year.getFullYear()
        : Number(this.form.year)

      const { moralScore, academicScore, researchScore, serviceScore } = this.form

      // 范围校验
      if (
        moralScore < 0 || moralScore > 30 ||
        academicScore < 0 || academicScore > 20 ||
        researchScore < 0 || researchScore > 50 ||
        serviceScore < 0 || serviceScore > 20
      ) {
        ElMessage.error('请填写正确范围内的分数')
        return
      }

      const payload = {
        year: yearVal,
        studentId: this.studentId,
        moralScore,
        academicScore,
        researchScore,
        serviceScore,
        totalScore: this.totalScore,
        result: '未通过'
      }

      try {
        const res = await axios.post('/api/scholarshipapplications', payload, {
          headers: { 'Content-Type': 'application/json' },
          withCredentials: true
        })

        if (res.data === 1 || res.data === '1' || res.data.code === 200) {
          ElMessage.success('分数概况保存成功')
        } else {
          ElMessage.error(res.data.message || '保存失败，请稍后重试')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      }
    },

    resetForm() {
      this.form = {
        year: new Date().getFullYear(),
        moralScore: 0,
        academicScore: 0,
        researchScore: 0,
        serviceScore: 0
      }
    }
  }
}
</script>

<style scoped>
.summary-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 24px;
  background-color: #fafafa;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
</style>
